<template>
  <div class="login">
    <div class="container">
      <h1>Please Login</h1>
      <form :model="loginUser">
        <div class="form-control">
          <input type="text" required v-model="loginUser.email" />
          <label for="">Email</label>
        </div>
        <div class="form-control">
          <input type="password" required v-model="loginUser.password" />
          <label for="">Password</label>
        </div>
        <button
          class="btn"
          type="submit"
          @click.prevent="submitUser(loginUser)"
        >
          Login
        </button>
        <p>
          Don't have an account?
          <router-link to="/register">Register</router-link>
        </p>
      </form>
    </div>
  </div>
</template>

<script>
import jwt_decode from "jwt-decode";
import login from "../../public/js/login.js";
export default {
  name: "Login",
  data() {
    return {
      loginUser: {
        email: "",
        password: "",
      },
    };
  },
  mounted() {
    login();
  },
  methods: {
    isEmpty(value) {
      return (
        value === undefined ||
        value === null ||
        (typeof value === "object" && Object.keys(value).length === 0) ||
        (typeof value === "string" && value.trim().length === 0)
      );
    },
    submitUser(loginUser) {
      if (this.loginUser.email && this.loginUser.password) {
        this.$axios
          .post("/api/users/login", this.loginUser)
          .then((res) => {
            // if (res.status == 200) {
            console.log(res.data);
            //拿到token
            const { token } = res.data;
            console.log(token);
            //存入浏览器中
            localStorage.setItem("userToken", token);
            //解析token
            const decode = jwt_decode(token);
            console.log(decode);
            //token存储在vuex中
            this.$store.dispatch("setAuthenticated", !this.isEmpty(decode));
            this.$store.dispatch("setUser", decode);
            this.$message({
              message: "账号登录成功!",
              type: "success",
            });
            // alert("登录成功!");
            //登陆后跳转
            this.$router.push("/index");
            // }
          })
          .catch((err) => {
            // alert("用户名或者密码不正确");
          });
      } else {
        alert("格式不正确请重新输入");
        return false;
      }
    },
  },
};
</script>

<style scoped>
@import url("../../public/css/login.css");
</style>